package com.drore.logapp.http;


import com.drore.logapp.http.converter.StringConverterFactory;
import com.drore.logapp.http.interceptor.CheckCookiesInterceptor;
import com.drore.logapp.http.interceptor.HttpInterceptor;
import com.drore.logapp.http.interceptor.ReadCookiesInterceptor;
import com.drore.logapp.http.interceptor.SaveCookiesInterceptor;
import com.drore.logapp.http.converter.GsonConverterFactory;
import com.drore.logapp.utils.GlobalConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * desc
 *
 * @author sixbing
 * @date 2018/12/11 11:52
 */
public class RetrofitCookieUtil {
    private static RetrofitCookieUtil instance;
    private Retrofit retrofit;
    private OkHttpClient client;
    private static String TAG = "RetrofitCookieUtil";

    public static RetrofitCookieUtil getInstance() {
        if (instance == null)
            instance = new RetrofitCookieUtil();
        return instance;
    }

    private RetrofitCookieUtil() {
        client = new OkHttpClient.Builder()
                .addInterceptor(new HttpInterceptor())
                .addInterceptor(new CheckCookiesInterceptor())
                .addInterceptor(new ReadCookiesInterceptor())
                .addInterceptor(new SaveCookiesInterceptor())
                .readTimeout(15, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS)
                .build();
        retrofit = new Retrofit
                .Builder()
                .client(client)
                .baseUrl(GlobalConfig.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .build();
    }

    /**
     * 添加代理
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T getHttpApiString(String baseUrl, Class<T> tClass) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .client(client)  //设置网络请求，默认httpclient
                .build();
        T t = retrofit.create(tClass);
        return t;
    }

    /**
     * 添加代理
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T getHttpApi(String baseUrl, Class<T> tClass) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .client(client)  //设置网络请求，默认httpclient
                .build();
        T t = retrofit.create(tClass);
        return t;
    }
}
